package thread.lockAndCondition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Description: one by one by one using condition
 * Created by E440 on 2017/4/24.
 */
public class ConditionTest {
    static public void main(String[] args){
        ConditionTest oneByOne=new ConditionTest();
        oneByOne.test();

    }

    public  void test(){
        final  Business business=new Business();

        new Thread(){
            public void run(){
                for(int i=1;i<10;i++){
                    business.sub1(i);
                }
            }
        }.start();

        new Thread(){
            public void run(){
                for(int i=1;i<=10;i++){
                    business.sub2(i);
                }
            }
        }.start();

        new Thread(){
            public void run(){
                for(int i=1;i<=10;i++){
                    business.sub3(i);
                }
            }
        }.start();
    }

    class Business{
        int signal=0;
        Lock lock=new ReentrantLock();
        Condition condition1=lock.newCondition();
        Condition condition2=lock.newCondition();
        Condition condition3=lock.newCondition();

        public  void sub1(int j){
            lock.lock();
            while(signal!=0){
                try {
                    condition1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for(int i=1;i<=10;i++){
                System.out.println("j=" + j + " i="+i+" : sub1 is running.");
            }
            signal=1;
            condition2.signal();
            lock.unlock();
        }

        public  void sub2(int j){
            lock.lock();
            while(signal!=1){
                try {
                    condition2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for(int i=1;i<=10;i++){
                System.out.println("j=" + j + " i="+i+" : sub2 is running.");
            }
            signal=2;
            condition3.signal();
            lock.unlock();
        }

        public  void sub3(int j){
            lock.lock();
            while(signal!=2){
                try {
                    condition3.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for(int i=1;i<=10;i++){
                System.out.println("j=" + j + " i="+i+" : sub3 is running.");
            }
            signal=0;
            condition1.signal();
            lock.unlock();
        }
    }
}
